package org.example.juc.lock;

import java.util.TreeMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 消费者
 */
public class LockDBTest {
    public static void main(String[] args) throws Exception{
        // 1一个生产者
        // 10个消费者
        LockDB lockDB = new LockDB();
        int MAX_THREAD = 10;
        ExecutorService service = Executors.newFixedThreadPool(MAX_THREAD);
        CountDownLatch latch = new CountDownLatch(100);

        for (int i = 0; i < MAX_THREAD * 10; i++) {
            service.submit(new Runnable() {
                @Override
                public void run() {
                    Integer conn = null;
                    try {
                        conn = lockDB.getConnection();
                        System.out.println("获取到资源 = " + conn);

                        // 进行业务逻辑处理
                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (conn != null) {
                            // 归还连接
                            lockDB.close(conn);
                        }
                        latch.countDown();
                    }
                }
            });
        }

        latch.await();
        service.shutdown();
        System.out.println("总的连接 = " + lockDB.getResources() + ", 活动连接 = " + lockDB.getActiveCount());
    }
}
